package cn.le.agent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by admin on 2017/6/1.
 *jdk动态代理,代理类需要实现InvocationHandler接口
 *动态代理可以将所有调用重定向到调用的处理器,因此通常会像调用的处理器的构造器传递一个"实际"对象的引用
 * 从而使得调用处理器在执行其中介任务时,可以将请求转发
 *
 *
 */
public class DynmicProxyHandler implements InvocationHandler{

    private Object proxied;
    public DynmicProxyHandler(Object proxied)
    {
        this.proxied = proxied;
    }
    //invoke()方法中传递进来了代理对象,以防止需要区分请求的来源,当是在许多情况下,并不关心这一点,
    //在invoke()内部,在代理上调用方法时需要格外当心,因为对接口的调用被重定向为代理的调用
    public Object invoke(Object proxied, Method method,Object[] args)throws Throwable
    {
        System.out.println("*********** proxy ");
        if(args != null)
        {
            for (Object arg : args)
            {
                System.out.println(" "+arg);
            }
        }
        Object obj = null;
        try
        {
         obj = method.invoke(this.proxied,args);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

        return obj;
    }
}

class SimpleDynamicProxy{

    public static void consumer(Interface iface)
    {
        iface.doSomething();
        iface.somethingElse("bonobo");
    }

    public static void main(String[] args)
    {
        RealObject real = new RealObject();
        consumer(real);

        try {
            Interface proxy = (Interface) Proxy.newProxyInstance(
                    Interface.class.getClassLoader(),new Class[]{Interface.class},
                    new DynmicProxyHandler(new SimpleProxy()));

            consumer(proxy);

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}










